package com.hss.thread.wait;

import com.hss.thread.TestCallable;

import java.util.Random;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;

public class WaitThread_CountDownLatch {
    public static final int TEST_THREAD_COUNT = 10;
    public static void printSortedResult(Vector<Integer> list) {
        for (Integer item : list) {
            System.out.println(item == null ? "null" : item);
        }
    }
    public static void test(){
        final Vector<Integer> list = new Vector<>();
        Thread[] threads = new Thread[TEST_THREAD_COUNT];
        Random random = new Random();
        final CountDownLatch latch = new CountDownLatch(TEST_THREAD_COUNT);
        for (int i=0;i <TEST_THREAD_COUNT;i++){
            final int num = i;
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(random.nextInt(100));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    list.add(num);
                    System.out.print(num + " add.\t");
                     latch.countDown();
                    System.out.println(num + " latch.countDown()  after");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(num + " latch.countDown()  after 5000");

                }
            });
            threads[i].start();
        }

        try {
            //(await)count个线程或一个线程count次计数，通过工作线程来countDown计数减一，直到计数为0，await阻塞结束。
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        printSortedResult(list);

    }

    public static void main(String[] args) {
        test();
    }
}
